!function () {
    function checkuserlogin(url,redirecturl)
    {
        $$.ajax({
            contentType:'OPTIONS',
            crossDomain:true,
            method:'GET',
            async:false,
            url:url,
            data:{},
            dataType:'json',
            xhrFields:{"withCredentials":true},
            success:function (res) {
                //console.log('用户登陆',res);
                if (res.code == 0){
                    window.location.href = redirecturl;
                } else {
                    GlobalUserid = parseInt(res.data.uid);
                    GlobalOpenid = res.data.wx_openid;
                    GlobalFirst = res.data.isfirst;
                    // Globaltoken = res.data.token;
                    //console.log(GlobalUserid,GlobalOpenid);
                }
            }
        });
    }
    function showNfirst(isfirst){
        if (isfirst==0){
            var html='<div class="popup" style="background: transparent;padding-bottom: 40px;">'+
                '<div class="flex-column flex-justify-center flex-align-center" style="width: 100%;height: 100%;">'+
                '<img src="http://wap.nldou.com/comm/img/notify.png" style="width: 70%;">'+
                '<div style="margin-top: 20px;">'+
                '<i class="f7-icons color-green close-popup" style="font-size: 40px;width: 40px;height: 40px;">'+
                'close_round_fill</i></div>'+
                '</div>'+
                '</div>';
            Nldouapp.popup(html);
        }
    }
// function nativepay(num){
//     $$.ajax({
//         contentType:'OPTIONS',
//         crossDomain:true,
//         url:Nativepay_url,
//         method:"POST",
//         data: {num:num,uid:GlobalUserid},
//         dataType:'json',
//         success: function (res) {
//             //console.log('扫码统一下单',res);
//             //alert(JSON.stringify(res));
//             if(res.code==1){
//                 chargestatus=false;
//                 mainView.router.load({url:'nativepay.html',context:res.data});
//             }else{
//                 //console.log(res.msg);
//                 Nldouapp.alert('下单失败,请重试','');
//                 chargestatus=false;
//             }
//         },
//         error:function (res) {
//             alert(JSON.stringify(res));
//             Nldouapp.alert('下单失败,请重试','');
//             chargestatus=false;
//         }
//     });
// }
    function crosspay(num)
    {
        var fee = 0;
        switch (parseInt(num)){
            case 50:
                fee = "0.5";
                break;
            case 100:
                fee = "1";
                break;
            case 500:
                fee = "4.98";
                break;
            case 1000:
                fee = "9.95";
                break;
            case 5000:
                fee = "49.5";
                break;
            case 10000:
                fee = "98.5";
                break;
            case 20000:
                fee = "196.5";
                break;
            case 50000:
                fee = "490";
                break;
            default:
                return false;
        }
        mainView.router.load({url:'nativepay.html',context:{num:num,fee:fee}});
    }
    function pay(num) {
        $$.ajax({
            contentType:'OPTIONS',
            crossDomain:true,
            url:Prepay_url,
            method:"POST",
            data: {num:num,uid:GlobalUserid,openid:GlobalOpenid},
            dataType:'json',
            success: function (res) {
                //console.log('统一下单',res);
                if(res.code==1){
                    wx.chooseWXPay({
                        timestamp: res.data.timeStamp,
                        nonceStr: res.data.nonceStr,
                        package: res.data.package,
                        signType: res.data.signType,
                        paySign: res.data.paySign,
                        success: function (res) {
                            //console.log('支付成功',res);
                            Nldouapp.alert('您已成功充值'+num+'个能量豆','');
                            if($$('#Ucenter .beansnum').length > 0) {
                                var beans = parseInt($$('#Ucenter .beansnum').data('beans'));
                                var add = parseInt(num);
                                var total = beans+add;
                                $$('#Ucenter .beansnum').data('beans',total);
                                $$('#Ucenter .beansnum').html(total);
                            }
                            chargestatus=false;
                        },
                        fail:function(){
                            chargestatus=false;
                            crosspay(num);
                        },
                        cancel:function () {
                            chargestatus=false;
                        }
                    });
                }else{
                    //console.log(res.msg);
                    Nldouapp.alert('下单失败,请重试','');
                    chargestatus=false;
                }
            },
            error:function () {
                Nldouapp.alert('下单失败,请重试','');
                chargestatus=false;
            }
        });
    }
    function sharecallback(url,sharetype)
    {
        request(Sharecallback_url,'POST',{uid:GlobalUserid,url:url,type:sharetype},function (res) {
            if (res.code==1&&res.data.firstshare){
                var html = '<div class="flex-row flex-nowrap flex-justify-center flex-align-center">' +
                    '<i class="f7-icons color-green bold" style="margin-right: 15px;width: 25px;height: 25px;">alarm</i>' +
                    '<span class="pubinfo bold">首次分享成功,获得100能量豆</span>' +
                    '</div>';
                Nldouapp.modal({text:html});
                setTimeout(function () {
                    Nldouapp.closeModal('.modal');
                    $$('.modal').remove();
                    $$('.modal-overlay-visible').remove();
                },2000);
            }
        });
    }
    function setShare(title,url,desc){
        //console.log('setshare:'+title+';'+desc+';'+url);
        wx.onMenuShareTimeline({
            title: title,
            link: url,
            imgUrl: Shareimg_url,
            success: function () {
                sharecallback(url,'timeline');
                return true;
            }
        });
        wx.onMenuShareAppMessage({
            title: title,
            desc: desc,
            link: url,
            imgUrl: Shareimg_url,
            type: 'link',
            success: function () {
                sharecallback(url,'appmsg');
                return true;
            }
        });
    }
    function getShareContent() {
        var curpage = $$('.view-main').data('page');
        var share = {};
        switch (curpage){
            case 'Subject':
                share.title = $$('#Subject').data('sharetitle');
                share.desc = $$('#Subject').data('sharedesc');
                var sid = $$('#Subject').data('id');
                share.url = Share_url+'&page=subject'+'&param=sid.'+sid;
                break;
            case 'Question':
            case 'Beansrank':
            case 'Dechargebeans':
                share.title = $$('#Question').data('sharetitle');
                share.desc = $$('#Question').data('sharedesc');
                var qid = $$('#Question').data('id');
                share.url = Share_url+'&page=question'+'&param=qid.'+qid;
                break;
            case 'Answer':
                share.title = $$('#Answer').data('sharetitle');
                share.desc = $$('#Question').data('sharedesc');
                var aid = $$('#Answer').data('id');
                share.url = Share_url+'&page=answer'+'&param=aid.'+aid;
                break;
            case 'Questionrank':
                share.title = '一问奕答女神榜';
                share.desc = '您的朋友邀请您，为他困扰的问题贡献一份力哦~~';
                share.url = Share_url+'&page=questionrank';
                break;
            default:
                share.title = '一问奕答';
                share.desc = '复旦大学社会学教授沈奕斐，为您解答家庭教育的各类问题，陪您共走育儿路';
                share.url = Share_url;
        }
        return share;
    }
    function sofa(length,container) {
        container.find('.sofa').remove();
        if(length == 0) {
            var html = Nldouapp.SofaTemplate();
            container.append(html);
        }
    }
    function contentempty(length,content,container) {
        container.find('.empty').remove();
        if(length == 0) {
            var html = Nldouapp.EmptyTemplate({content:content});
            container.append(html);
        }
    }
    function request(url,method,data,success){
        // data.uid = GlobalUserid;
        // data.token = Globaltoken;
        $$.ajax({
            method:method,
            url:url,
            data:data,
            dataType:'json',
            success:success
        });
    }
    function prequest(url,method,data,success,error){
        // data.uid = GlobalUserid;
        // data.token = Globaltoken;
        $$.ajax({
            contentType:'OPTIONS',
            crossDomain:true,
            method:method,
            url:url,
            data:data,
            timeout:5000,
            dataType:'json',
            success:success,
            error:error
        });
    }
    /******个人中心******/
    function getUcInfo(url)
    {
        request(url,'POST',{uid:GlobalUserid},function (res) {
            //console.log('个人中心信息',url,res);
            if (res.code == 1){
                var html = Nldouapp.UcHeaderTemplate(res.data);
                $$('#Ucenter .ucheader').html(html);
                // $$('.ucnav .center').html(res.data.userName);
            }
        });
    }
    function signComplete(beans)
    {
        var html = '<div class="flex-row flex-nowrap flex-justify-center flex-align-center">' +
            '<i class="f7-icons color-green bold" style="margin-right: 15px;width: 25px;height: 25px;">alarm</i>' +
            '<span class="pubinfo bold">签到成功,获得10颗能量豆</span>' +
            '</div>';
        Nldouapp.modal({text:html});
        setTimeout(function () {
            Nldouapp.closeModal();
            $$('#Ucenter .beansnum').html(beans);
            var signbtn = $$('#Ucenter .signbtn');
            signbtn.removeClass('bg-green');
            signbtn.removeClass('signbtn');
            signbtn.addClass('bg-gray');
            signbtn.html('今日已签');
        },2000);
    }
    function signToday(url)
    {
        prequest(url,'POST',{uid:GlobalUserid},function (res) {
            //console.log('个人中心签到',url,res);
            if (res.code == 1){
                if (res.data.beans == 0){
                    Nldouapp.alert('今日已经签到了');
                }else{
                    signComplete(res.data.beans);
                }
            }
        },function () {
            Nldouapp.alert('系统繁忙，请重试','');
        });
    }
    function uploadimage(mediaid)
    {
        request(Uploadimg_url,'POST',{uid:GlobalUserid,mediaid:mediaid},function (res){
            //alert(JSON.stringify(res));
        })
    }
    function changeicon(localid)
    {
        //生成预览
        wx.getLocalImgData({
            localId: localid,
            success: function (res) {
                var localData = res.localData;
                $$('#Ucenter .editiconbtn').attr('src',localData);
            }
        });
        //上传到服务器
        wx.uploadImage({
            localId: localid,
            isShowProgressTips: 1,
            success: function (res) {
                uploadimage(res.serverId);
            }
        });
    }
    function getCity(cityselected,areaselected)
    {
        request(Getcity_url,'GET',{},function (res) {
            //console.log('获取城市列表',res);
            if (res.code == 1){
                var html = Nldouapp.CitylistTemplate(res.data);
                $$('select[name="livecity"]').html(html);
                if (cityselected) {
                    $$('select[name="livecity"]').val(cityselected);
                    var cityname = $$('select[name="livecity"]').find('option[value="'+cityselected+'"]').html();
                    $$('select[name="livecity"]').parent().find('.item-after').html(cityname);
                    getArea(cityselected,areaselected);
                }
            }
        });
    }
    function getArea(cityselected,areaselected)
    {
        request(Getarea_url,'POST',{cityid:cityselected},function (res) {
            //console.log('获取区域列表',res);
            if (res.code == 1){
                var html = Nldouapp.ArealistTemplate(res.data);
                $$('select[name="livearea"]').html(html);
                if (areaselected) {
                    $$('select[name="livearea"]').val(areaselected);
                    var areaname = $$('select[name="livearea"]').find('option[value="'+areaselected+'"]').html();
                    $$('select[name="livearea"]').parent().find('.item-after').html(areaname);
                }
            }
        });
    }
    function getProfile()
    {
        request(Getprofile_url,'POST',{uid:GlobalUserid},function (res) {
            //console.log('个人信息列表',res);
            var phtml = Nldouapp.ProfilelistTemplate(res.data.user);
            $$('form#Profileform').html(phtml);
            Nldouapp.calendar({
                input:'#bcal',
                monthNames:['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'],
                weekHeader:false,
                closeOnSelect:true
            });
            getCity(res.data.user.livecity,res.data.user.livearea);
            $$('select[name="livecity"]').on('change',function () {
                var cityid = $$(this).val();
                getArea(cityid);
                $$('select[name="livearea"]').parent().find('.item-after').html('');
            });
            var chtml = Nldouapp.ChilditemTemplate(res.data.child);
            $$('#Profile .child-wrap').append(chtml);
        });
    }
    function checkProfile() {
        var data = Nldouapp.formToData('#Profileform');
        var userName = data['userName'].replace(/\s/g,"");
        var wc = userName.length;
        if (wc == 0) {Nldouapp.alert('请输入姓名','');profileuploading = false;return false;}

        var userGender = data['userGender'];
        wc = userGender.length;
        if (wc == 0) {Nldouapp.alert('请选择性别','');profileuploading = false;return false;}

        var telNum = data['telNum'];
        if(!(/^1\d{10}$/).test(telNum)){Nldouapp.alert('请输入正确的11位手机号','');profileuploading = false;return false;}

        var wx_num = data['wx_num'].replace(/^\s|\s$/,"");

        var email = data['email'].replace(/\s/g,"");
        wc = email.length;
        if (wc>0 && email.indexOf('@') == -1) {Nldouapp.alert('请输入正确的邮箱','');profileuploading = false;return false;}

        var birthDay = data['birthDay'];
        var eduLevel = data['eduLevel'];
        var livecity = data['livecity'];
        var livearea = data['livearea'];

        var child = [];
        $$('.child-wrap .childitem').each(function () {
            var id = $$(this).data('id');
            var cg = $$(this).data('gender');
            var cs = $$(this).data('school');
            var cb = $$(this).data('birth');
            child.push({'id':id,'gender':cg,'birthDay':cb,'school':cs});
        });

        var result = {'uid':GlobalUserid,'userName':userName,'userGender':userGender,'telNum':telNum,'wx_num':wx_num,'email':email
            ,'birthDay':birthDay,'eduLevel':eduLevel,'livecity':livecity,'livearea':livearea,'child':child,'childdelete':childdelte};

        return result;
    }
    function subprofile(data)
    {
        startupload();
        request(Subprofile_url,'POST',data,function (res) {
            //console.log('上传个人信息',res);
            if (res.code == 1){
                completeupload();
                if(res.data.firstprofile){
                    firstupload('首次提交信息,获得100能量豆');
                }
                profileuploading=false;
                mainView.router.back();
            }else{
                failupload();
                profileuploading=false;
            }
        });
    }
    function getMyfollowq(url,page,append)
    {
        if (!append) {
            $$('#Myfollows .followlist').find('a').remove();
            $$('#Myfollows .infinite-scroll').find('.infinite-scroll-preloader').remove();
            var modal = '<div class="infinite-scroll-preloader">'+
                '<div class="preloader"></div>'+
                '</div>';
            $$('#Myfollows .infinite-scroll').append(modal);

        }
        request(url,'POST',{uid:GlobalUserid,pagesize:myfollowspagesize,page:page},function (res) {
            //console.log('个人中心我的关注问题',res);
            if (res.code == 1){
                var html = Nldouapp.QitemTemplate(res.data.question);
                if (!append){
                    Nldouapp.attachInfiniteScroll('#Myfollows .infinite-scroll');
                    contentempty(res.data.question.length,'还没有关注的内容~~',$$('#Myfollows .followlist'));
                }
                $$('#Myfollows .followlist').append(html);
            }
            if (res.data.end == 1){
                Nldouapp.detachInfiniteScroll($$('#Myfollows .infinite-scroll'));
                $$('#Myfollows .infinite-scroll-preloader').remove();
            }
            contentempty($$("#Myfollows .followlist").find('a').length,'还没有关注的内容~~',$$("#Myfollows .followlist"));
            myfollowsloading = false;
        });

    }
    function getMyfollowsub(url,page,append)
    {
        if (!append) {
            $$('#Myfollows .followlist').find('a').remove();
            $$('#Myfollows .infinite-scroll').find('.infinite-scroll-preloader').remove();
            var modal = '<div class="infinite-scroll-preloader">'+
                '<div class="preloader"></div>'+
                '</div>';
            $$('#Myfollows .infinite-scroll').append(modal);
        }
        request(url,'POST',{uid:GlobalUserid,pagesize:myfollowspagesize,page:page},function (res) {
            //console.log('个人中心我的关注话题',res);
            if (res.code == 1){
                var html = Nldouapp.SubitemTemplate(res.data.subject);
                if (!append){
                    Nldouapp.attachInfiniteScroll('#Myfollows .infinite-scroll');
                    contentempty(res.data.subject.length,'还没有关注的内容~~',$$('#Myfollows .followlist'));
                }
                $$('#Myfollows .followlist').append(html);
            }
            if (res.data.end == 1){
                Nldouapp.detachInfiniteScroll($$('#Myfollows .infinite-scroll'));
                $$('#Myfollows .infinite-scroll-preloader').remove();
            }
            contentempty($$("#Myfollows .followlist").find('a').length,'还没有关注的内容~~',$$("#Myfollows .followlist"));
            myfollowsloading = false;
        });
    }
    function getMycollect(url,page,append)
    {
        request(url,'POST',{uid:GlobalUserid,pagesize:mycollectspagesize,page:page},function (res) {
            //console.log('个人中心我的收藏',res);
            if (res.code == 1){
                var html = Nldouapp.CollectitemTemplate(res.data.answer);
                if (!append) {
                    $$('#Mycollects .collectlist').find('.aitem').remove();
                    $$('#Mycollects .infinite-scroll').find('.infinite-scroll-preloader').remove();
                    var modal = '<div class="infinite-scroll-preloader">'+
                        '<div class="preloader"></div>'+
                        '</div>';
                    $$('#Mycollects .infinite-scroll').append(modal);
                    Nldouapp.attachInfiniteScroll('#Mycollects .infinite-scroll');
                    contentempty(res.data.answer.length,'还没有收藏的回答~~',$$('#Mycollects .collectlist'));
                }
                $$('#Mycollects .collectlist').append(html);

            }
            if (res.data.end == 1){
                Nldouapp.detachInfiniteScroll($$('#Mycollects .infinite-scroll'));
                $$('#Mycollects .infinite-scroll-preloader').remove();
            }
            contentempty($$("#Mycollects .collectlist").find('a').length,'还没有收藏的回答~~',$$("#Mycollects .collectlist"));
            mycollectsloading = false;
        });
    }
    function getMyanswer(url,page,append)
    {
        request(url,'POST',{uid:GlobalUserid,pagesize:myanswerpagesize,page:page},function (res) {
            //console.log('个人中心我的回答',url,res);
            if (res.code == 1){
                var html = Nldouapp.MyansweritemTemplate(res.data.answer);
                if (!append) {
                    $$('#Myanswers .myanswerlist').find('.aitem').remove();
                    $$('#Myanswers .infinite-scroll').find('.infinite-scroll-preloader').remove();
                    var modal = '<div class="infinite-scroll-preloader">'+
                        '<div class="preloader"></div>'+
                        '</div>';
                    $$('#Myanswers .infinite-scroll').append(modal);
                    Nldouapp.attachInfiniteScroll('#Myanswers .infinite-scroll');
                    contentempty(res.data.answer.length,'还没有回答过问题~~',$$('#Myanswers .myanswerlist'));
                }
                $$('#Myanswers .myanswerlist').append(html);

            }
            if (res.data.end == 1){
                Nldouapp.detachInfiniteScroll($$('#Myanswers .infinite-scroll'));
                $$('#Myanswers .infinite-scroll-preloader').remove();
            }
            contentempty($$("#Myanswers .myanswerlist .aitem").length,'还没有回答过问题~~',$$("#Myanswers .myanswerlist"));
            myanswerloading = false;
        });
    }
    function getMyquestion(url,page,append)
    {
        request(url,'POST',{uid:GlobalUserid,pagesize:myquestionpagesize,page:page},function (res) {
            //console.log('个人中心我的提问',url,res);
            if (res.code == 1){
                var html = Nldouapp.MyquestionitemTemplate(res.data.question);
                if (!append) {
                    $$('#Myquestions .myqlist').find('.qitem').remove();
                    $$('#Myquestions .infinite-scroll').find('.infinite-scroll-preloader').remove();
                    var modal = '<div class="infinite-scroll-preloader">'+
                        '<div class="preloader"></div>'+
                        '</div>';
                    $$('#Myquestions .infinite-scroll').append(modal);
                    Nldouapp.attachInfiniteScroll('#Myquestions .infinite-scroll');
                    contentempty(res.data.question.length,'还没有提问~~',$$('#Myquestions .myqlist'))
                }
                $$('#Myquestions .myqlist').append(html);

            }
            if (res.data.end == 1){
                Nldouapp.detachInfiniteScroll($$('#Myquestions .infinite-scroll'));
                $$('#Myquestions .infinite-scroll-preloader').remove();
            }
            contentempty($$("#Myquestions .myqlist .qitem").length,'还没有提问~~',$$("#Myquestions .myqlist"));
            myquestionloading = false;
        });
    }
// function checkcharge(num) {
//     num = num.replace(/\s/g,"");
//     if(!(/^[1-9][0-9]*$/).test(num)){
//         Nldouapp.alert('请输入正确的金额');
//         return false;
//     }
//     return parseInt(num);
// }
    /******发现页******/
    function getDiscoverData(url)
    {
        request(url,'POST',{},function (res) {
            //console.log('发现页信息',url,res);
            if (res.code == 1){
                var banner = res.data.banner;
                var subject = res.data.subject;
                var bannerhtml = Nldouapp.SwiperslideTemplate(banner);
                var subhtml = Nldouapp.SwiperslideRectTemplate(subject);

                $$('#Discover .swiper-discover .swiper-wrapper').html(bannerhtml);
                $$('#Discover .swiper-subject .swiper-wrapper').html(subhtml);

                Nldouapp.swiper('.swiper-discover',{
                    autoplay:4000,
                    // loop:true,
                    pagination:'.swiper-pagination-discover'
                });
                Nldouapp.swiper('.swiper-subject',{
                    slidesPerView:'auto',
                    spaceBetween:10,
                    freeMode:true
                });
            }
        });
    }
    function getQuestion(page,url,append)
    {
        if (!append) {
            $$('#Discover .qlist').find('.qitem').remove();
            $$('#Discover .infinite-scroll').find('.infinite-scroll-preloader').remove();
            var modal = '<div class="infinite-scroll-preloader">'+
                '<div class="preloader"></div>'+
                '</div>';
            $$('#Discover .infinite-scroll').append(modal);
            Nldouapp.attachInfiniteScroll('#Discover .infinite-scroll');
        }
        request(url,'POST',{page:page,pagesize:discoverpagesize},function (res) {
            //console.log('发现页问题列表',res);
            setTimeout(function () {
                if (res.code == 1){
                    var qhtml = Nldouapp.QitemTemplate(res.data.question);
                    $$('#Discover .qlist').append(qhtml);
                }
                if (res.data.end == 1){
                    Nldouapp.detachInfiniteScroll($$('#Discover .infinite-scroll'));
                    $$('#Discover .infinite-scroll-preloader').remove();
                }
                discoverloading = false;
            },1000);
        });
    }
    function getNotifyCount(url)
    {
        request(url,'POST',{uid:GlobalUserid},function (res) {
            //console.log('消息icon',res);
            if (res.code==1){
                Sysmsgnum = parseInt(res.data.sys);
                Usermsgnum = parseInt(res.data.user);
                var html = Nldouapp.NotifyiconTemplate({unread:res.data.unread});
                $$('.toolbar .notifyicon').remove();
                $$('.toolbar .notifybtn').append(html);
            }
        });
    }
    function readNotify(url,msgid,msgtype)
    {
        request(url,'POST',{uid:GlobalUserid,msgid:msgid,msgtype:msgtype},function () {
            //console.log('阅读消息',res);
        });
    }
    function clearNotify(url)
    {
        request(url,'POST',{uid:GlobalUserid},function (res) {
            //console.log('清空消息',res);
            $$('#Notify .notifylistwrap').find('li').remove();
        });
    }
    function getUserNotify(url,page,append)
    {
        $$('#Notify .toolbar').show();
        if (!append){
            $$('#Notify .notifylistwrap').find('li').remove();
            $$('#Notify .infinite-scroll').find('.infinite-scroll-preloader').remove();
            var modal = '<div class="infinite-scroll-preloader">'+
                '<div class="preloader"></div>'+
                '</div>';
            $$('#Notify .infinite-scroll').append(modal);
        }
        request(url,'POST',{uid:GlobalUserid,page:page,pagesize:notifypagesize},function (res) {
            //console.log('消息列表',res);
            if (res.code == 1){
                var html = Nldouapp.NotifylistTemplate(res.data);
                if (!append){
                    Nldouapp.attachInfiniteScroll('#Notify .infinite-scroll');
                    contentempty(res.data.notify.length,'还没有消息~~',$$('#Notify .notifylistwrap'));
                }
                $$('#Notify .notifylistwrap').append(html);
            }
            if (res.data.end == 1){
                Nldouapp.detachInfiniteScroll($$('#Notify .infinite-scroll'));
                $$('#Notify .infinite-scroll-preloader').remove();
            }
            contentempty($$('#Notify .notifylistwrap').find('li').length,'还没有消息~~',$$('#Notify .notifylistwrap'));
            notifyloading = false;
        });
    }
    function getSysNotify(url,page,append)
    {
        $$('#Notify .toolbar').hide();
        if (!append){
            $$('#Notify .notifylistwrap').find('li').remove();
            $$('#Notify .infinite-scroll').find('.infinite-scroll-preloader').remove();
            var modal = '<div class="infinite-scroll-preloader">'+
                '<div class="preloader"></div>'+
                '</div>';
            $$('#Notify .infinite-scroll').append(modal);
        }
        request(url,'POST',{uid:GlobalUserid,page:page,pagesize:notifypagesize},function (res) {
            //console.log('系统通知列表',res);
            if (res.code == 1){
                var html = Nldouapp.NotifylistTemplate(res.data);
                if (!append){
                    Nldouapp.attachInfiniteScroll('#Notify .infinite-scroll');
                    contentempty(res.data.notify.length,'还没有通知~~',$$('#Notify .notifylistwrap'));
                }
                $$('#Notify .notifylistwrap').append(html);
            }
            if (res.data.end == 1){
                Nldouapp.detachInfiniteScroll($$('#Notify .infinite-scroll'));
                $$('#Notify .infinite-scroll-preloader').remove();
            }
            contentempty($$('#Notify .notifylistwrap').find('li').length,'还没有通知~~',$$('#Notify .notifylistwrap'));
            notifyloading = false;
        });
    }
    /******话题页面******/
    function getSubById(url,sid) {
        request(url,'POST',{sid:sid,uid:GlobalUserid},function (res) {
            //console.log('话题页信息',url,res);
            if (res.code == 1){
                var title = '一问奕答话题-'+res.data.name;
                $$('#Subject').data('sharetitle',title);
                var desc = res.data.questions+'个问题，'+res.data.follows+'人关注';
                $$('#Subject').data('sharedesc',desc);

                if ($$('.view-main').data('page')==='Subject'){
                    var sid = $$('#Subject').data('id');
                    var url = Share_url+'&page=subject'+'&param=sid.'+sid;
                    setShare(title,url,desc);
                }


                var subhtml = Nldouapp.SubdetailTemplate(res.data);
                $$('#Subject .sub-header').append(subhtml);
            }
        });
    }
    function getQuestionBysid(url,page,sid,sort,append)
    {
        request(url,'POST',{page:page,sid:sid,sort:sort,pagesize:subjectpagesize},function (res) {
            //console.log('话题页问题列表',url,res);
            if (res.code == 1){
                var html = Nldouapp.QitemTemplate(res.data.question);
                if (!append) {
                    $$('#Subject .qlist').find('.qitem').remove();
                    $$('#Subject .infinite-scroll').find('.infinite-scroll-preloader').remove();
                    var modal = '<div class="infinite-scroll-preloader">'+
                        '<div class="preloader"></div>'+
                        '</div>';
                    $$('#Subject .infinite-scroll').append(modal);
                    Nldouapp.attachInfiniteScroll('#Subject .infinite-scroll');
                    sofa(res.data.question.length,$$("#Subject .qlist"));
                }
                $$('#Subject .qlist').append(html);

            }
            if (res.data.end == 1){
                Nldouapp.detachInfiniteScroll($$('#Subject .infinite-scroll'));
                $$('#Subject .infinite-scroll-preloader').remove();
            }
            subjectloading = false;
            sofa($$('#Subject .qlist .qitem').length,$$("#Subject .qlist"));
        });
    }
    function followSub(url,sid)
    {
        prequest(url,'POST',{sid:sid,uid:GlobalUserid},function (res) {
            fsubstatus = false;
            //console.log('用户关注话题',url,res);
        },function () {
            fsubstatus = false;
            Nldouapp.alert('系统繁忙，请重试','');
        })
    }
    function cancelfollowSub(url,sid)
    {
        prequest(url,'POST',{sid:sid,uid:GlobalUserid},function (res) {
            fsubstatus = false;
            //console.log('用户取消关注话题',url,res);
        },function () {
            fsubstatus = false;
            Nldouapp.alert('系统繁忙，请重试','');
        });
    }
    /******问题页面******/
    function readQuestion(url,qid){
        request(url,'POST',{qid:qid,uid:GlobalUserid},function (res) {
            //console.log('用户阅读问题',url,res);
        });
    }
    function getContributer(url,qid)
    {
        request(url,'POST',{qid:qid,pagesize:contripagesize},function (res) {
            //console.log('问题页贡献者信息',url,res);
            if (res.code == 1){
                var conhtml = Nldouapp.QContributerTemplate(res.data);
                $$('#Question .contribute-wrap .contributer').html(conhtml);
                $$('#Question .contribute-wrap .contrnum').html(res.data.contrnum);
                $$('#Question .contribute-wrap .beansnum').html(res.data.beansnum);
            }
        });
    }
    function getQuestionById(qid,url)
    {
        request(url,'POST',{qid:qid,uid:GlobalUserid},function (res) {
            //console.log('问题页信息',res);
            if (res.code == 1){
                var title = res.data.question;
                $$('#Question').data('sharetitle',title);
                // var desc = res.data.answers+'个回答，'+res.data.follows+'人关注';
                var desc = '复旦大学社会学教授沈奕斐，为您解答家庭教育的各类问题，陪您共走育儿路';
                $$('#Question').data('sharedesc',desc);

                if($$('.view-main').data('page')==='Question') {
                    var qid = $$('#Question').data('id');
                    var url = Share_url+'&page=question'+'&param=qid.'+qid;
                    setShare(title,url,desc);
                }

                var qhtml = Nldouapp.QdetailTemplate(res.data);
                var qwraphtml = Nldouapp.QdetailwrapTemplate({'link':res.data.anslink,'isresponsed':parseInt(res.data.isresponsed)});
                $$('#Question .qdetail-header').append(qhtml);
                $$('#Question .qdetail-wrap').append(qwraphtml);
                if(res.data.isresponsed==0) getContributer(Getcontributer_url,res.data.id);
            }
        });
    }
    function getAnswerByQid(qid,page,url,sort,append) {
        request(url,'POST',{qid:qid,page:page,sort:sort,pagesize:questionpagesize},function (res) {
            //console.log('问题答案列表',url,res);
            if (res.code == 1){
                var html = Nldouapp.AnsweritemTemplate(res.data);
                if (!append) {
                    $$('#Question .answerlist').find('.aitem').remove();
                    $$('#Question .infinite-scroll').find('.infinite-scroll-preloader').remove();
                    var modal = '<div class="infinite-scroll-preloader">'+
                        '<div class="preloader"></div>'+
                        '</div>';
                    $$('#Question .infinite-scroll').append(modal);
                    Nldouapp.attachInfiniteScroll('#Question .infinite-scroll');
                    sofa(res.data.answer.length,$$('#Question .answerlist'));
                }
                $$('#Question .answerlist').append(html);
            }
            if (res.data.end == 1){
                Nldouapp.detachInfiniteScroll($$('#Question .infinite-scroll'));
                $$('#Question .infinite-scroll-preloader').remove();
            }
            sofa($$('#Question .answerlist .aitem').length,$$('#Question .answerlist'));
            questionloading = false;
        });
    }
    function followQuestiion(url,qid)
    {
        prequest(url,'POST',{qid:qid,uid:GlobalUserid},function (res) {
            fqstatus = false;
            //console.log('用户关注问题',url,res);
        },function () {
            fqstatus = false;
            Nldouapp.alert('系统繁忙，请重试','');
        });
    }
    function cancelfollowQuestiion(url,qid)
    {
        prequest(url,'POST',{qid:qid,uid:GlobalUserid},function (res) {
            fqstatus = false;
            //console.log('用户取消关注问题',url,res);
        },function () {
            fqstatus = false;
            Nldouapp.alert('系统繁忙，请重试','');
        });
    }
    function getBeansrankByqid(url,page,qid)
    {
        request(url,'POST',{page:page,qid:qid,pagesize:rankpagesize},function (res) {
            //console.log('问题贡献榜列表',url,res);
            if (res.code == 1){
                var html = Nldouapp.RanklistTemplate(res.data);
                $$('#Beansrank .beansranklist').append(html);
                Nldouapp.detachInfiniteScroll($$('#Beansrank .infinite-scroll'));
                $$('#Beansrank .infinite-scroll-preloader').remove();
            }
        });
    }
    function getChargeUser(url) {
        request(url,'POST',{uid:GlobalUserid},function (res) {
            //console.log('充值页面',url,res);
            if (res.code == 1){
                var html = Nldouapp.ChargeuserTemplate(res.data);
                $$('#Chargebeans .user-wrap').html(html);
            }
        });
    }
    function getDechargeUser(url) {
        request(url,'POST',{uid:GlobalUserid},function (res) {
            //console.log('贡献页面',url,res);
            if (res.code == 1){
                var html = Nldouapp.ChargeuserTemplate(res.data);
                $$('#Dechargebeans .user-wrap').html(html);
            }
        });
    }
    function getQrank(url,page)
    {
        $$('#Questionrank .qlistwrap').find('a').remove();
        $$('#Questionrank .infinite-scroll').find('.infinite-scroll-preloader').remove();
        var modal = '<div class="infinite-scroll-preloader">'+
            '<div class="preloader"></div>'+
            '</div>';
        $$('#Questionrank .infinite-scroll').append(modal);
        request(url,'POST',{page:page,pagesize:rankpagesize},function (res) {
            //console.log('女神榜列表',url,res);
            if (res.code == 1){
                $$('#Questionrank .qlistwrap').find('.norankwrap').remove();
                var html = Nldouapp.QranklistTemplate(res.data);
                $$('#Questionrank .qlistwrap').append(html);
                Nldouapp.detachInfiniteScroll($$('#Questionrank .infinite-scroll'));
                $$('#Questionrank .infinite-scroll-preloader').remove();
            }
        });
    }
    function getQresponsed(url,page,append)
    {
        if (!append){
            $$('#Questionrank .qlistwrap').find('a').remove();
            $$('#Questionrank .infinite-scroll').find('.infinite-scroll-preloader').remove();
            var modal = '<div class="infinite-scroll-preloader">'+
                '<div class="preloader"></div>'+
                '</div>';
            $$('#Questionrank .infinite-scroll').append(modal);
        }
        request(url,'POST',{page:page,pagesize:rankpagesize},function (res) {
            //console.log('女神榜已回答列表',res);
            if (res.code == 1){
                $$('#Questionrank .qlistwrap').find('.norankwrap').remove();
                var html = Nldouapp.QreslistTemplate(res.data);
                if (!append){
                    Nldouapp.attachInfiniteScroll('#Questionrank .infinite-scroll');
                }
                $$('#Questionrank .qlistwrap').append(html);
            }
            if (res.data.end == 1){
                Nldouapp.detachInfiniteScroll($$('#Questionrank .infinite-scroll'));
                $$('#Questionrank .infinite-scroll-preloader').remove();
            }
            qrankloading = false;
        });
    }
    function dechargebeans(url,num,qid) {
        num = ("string" === typeof num)?num.replace(/\s/g,""):num.toString();
        if(!(/^[1-9][0-9]*$/).test(num)){
            Nldouapp.alert('请输入正确的数目');
            return false;
        }
        Nldouapp.showIndicator('');
        prequest(url,'POST',{uid:GlobalUserid,num:num,qid:qid},function (res) {
            //console.log('贡献能量豆',url,res);
            if (res.code == 1){
                Nldouapp.hideIndicator();
                Nldouapp.alert('您已成功贡献'+res.data.dechargenum+'个能量豆','');
                if($$('#Question .contrnum').length > 0) $$('#Question .contrnum').html(res.data.contributer);
                if($$('#Question .beansnum').length > 0) $$('#Question .beansnum').html(res.data.qbeans);
            }else{
                Nldouapp.hideIndicator();
                Nldouapp.alert('操作失败<br>您贡献的数目超过了您所拥有的能量豆哦');
            }
            dechargestatus=false;
        },function () {
            Nldouapp.hideIndicator();
            Nldouapp.alert('系统繁忙，请重试','');
            dechargestatus=false;
        });

    }
    /******提问回答上传状态******/
    function startupload()
    {
        var html = '<div class="flex-row flex-nowrap flex-justify-center flex-align-center loader-wrap">' +
            '<i class="f7-icons color-green hidden pubsucc" style="margin-right: 15px;width: 25px;height: 25px;">check</i>' +
            '<i class="f7-icons color-red hidden pubfail" style="margin-right: 15px;width: 25px;height: 25px;">close</i>' +
            '<span class="preloader pubproc" style="margin-right: 15px;width: 25px;height: 25px;"></span>' +
            '<span class="pubinfo bold">上传中</span>' +
            '</div>';
        Nldouapp.modal({text:html});
    }
    function completeupload()
    {
        var pubsucc = $$('.loader-wrap .pubsucc');
        var pubinfo = $$('.loader-wrap .pubinfo');
        var pubproc = $$('.loader-wrap .pubproc');
        pubproc.addClass('hidden');
        pubsucc.removeClass('hidden');
        pubinfo.html('上传成功');

        setTimeout(function () {
            Nldouapp.closeModal();
            $$('.popup-edit').remove();
            $$('.popup-qedit').remove();
            $$('.modal').remove();
            $$('.modal-overlay-visible').remove();
        },1000);
    }
    function failupload()
    {
        var pubfail = $$('.loader-wrap .pubfail');
        var pubinfo = $$('.loader-wrap .pubinfo');
        var pubproc = $$('.loader-wrap .pubproc');
        pubproc.addClass('hidden');
        pubfail.removeClass('hidden');
        pubinfo.html('系统繁忙，请重试');

        setTimeout(function () {
            Nldouapp.closeModal('.modal');
            $$('.modal').remove();
            $$('.modal-overlay-visible').remove();
        },2000)
    }
    function firstupload(content)
    {
        var html = '<div class="flex-row flex-nowrap flex-justify-center flex-align-center">' +
            '<i class="f7-icons color-green bold" style="margin-right: 15px;width: 25px;height: 25px;">alarm</i>' +
            '<span class="pubinfo bold">'+content+'</span>' +
            '</div>';
        setTimeout(function () {
            Nldouapp.modal({text:html});
        },1000);
        setTimeout(function () {
            Nldouapp.closeModal('.modal');
            $$('.modal').remove();
            $$('.modal-overlay-visible').remove();
        },3000);
    }
    /******提问页面******/
    function pubQuestion(url) {
        prequest(url,'POST',{},function (res) {
            //console.log('提问',url,res);
            if (res.code == 1){
                var html = Nldouapp.QeditorTemplate({subject:res.data});
                $$('body').append(html);
                Nldouapp.popup('.popup-qedit');
            }
        },function () {
            Nldouapp.alert('系统繁忙，请重试','');
        });
    }
    function checkQuestion(title,subject,desc)
    {
        title = title.replace(/\s/g,"");
        var wc = title.length;
        if (wc > 0) {
            if (wc > 50){
                Nldouapp.alert('问题不要超过50个字');
                return false;
            }
        }else{
            Nldouapp.alert('请填写标题');
            return false;
        }
        // if (!(/\?$/).test(title)){
        //     Nldouapp.alert('问题要以问号结尾');
        //     return false;
        // }
        // if (subject === 0){
        //     Nldouapp.alert('请选择话题');
        //     return false;
        // }
        // wc = desc.replace(/\s/g,"").length;
        // if (wc === 0){
        //     Nldouapp.alert('请填写描述');
        //     return false;
        // }
        desc = desc.replace(/\n|\r\n|\r/g,"<br>");
        return {title:title,subject:subject,desc:desc};
    }
    function addQuestion(url,subid,question,desc)
    {
        if (questionuploading === false){
            questionuploading = true;
            startupload();
            prequest(url,'POST',{uid:GlobalUserid,subid:subid,question:question,description:desc},function (res) {
                //console.log('用户添加问题',url,res);
                if (res.code == 1){
                    completeupload();
                    if(res.data.firstq){
                        firstupload('首次发布问题,获得100能量豆');
                    }
                    questionuploading=false;
                }else{
                    failupload();
                    questionuploading=false;
                }
            },function(){
                //console.log('ajax error');
                failupload();
                questionuploading=false;
            });
        }
    }
    /******回答页面******/
    function checkAnswerExist(url,qid,uid)
    {
        request(url,'POST',{qid:qid,uid:uid},function (res) {
            //console.log('判断用户是否回答过该问题',url,res);
            var ret = {};
            if (res.code == 0){
                ret = {type:'addAnswer',answer:'',aid:''};
            }else{
                var answer = res.data.answer.replace(/<br>|<\/p>/g,"\n").replace(/<p>/g,'');
                ret = {type:'updateAnswer',answer:answer,aid:res.data.aid};
            }
            var html = Nldouapp.EditorTemplate({'id':qid,'cid':ret.aid,'type':ret.type,'title':'添加观点','suggest':'填写观点内容','content':ret.answer});
            $$('body').append(html);
            Nldouapp.popup('.popup-edit');
        });
    }
    function checkAnswer(answer)
    {
        var wc = answer.replace(/\s/g,"").length;
        if (wc == 0) {
            Nldouapp.alert('请填写答案');
            return false;
        }
        answer = answer.replace(/\n|\r\n|\r/g,'<br>');
        return answer;
    }
    function addAnswer(url,qid,uid,answer)
    {
        if (answeruploading === false){
            answeruploading = true;
            startupload();
            prequest(url,'POST',{qid:qid,uid:uid,answer:answer},function (res) {
                //console.log('用户添加回答',url,res);
                if (res.code == 1){
                    completeupload();
                    if(res.data.firstans){
                        firstupload('首次发布观点,获得100能量豆');
                    }
                    answeruploading=false;
                    var qid = $$('#Question').data('id');
                    mainView.router.reloadPage('question.html?qid='+qid);
                }else{
                    failupload();
                    answeruploading=false;
                }
            },function(){
                //console.log('ajax error');
                failupload();
                answeruploading=false;
            })
        }
    }
    function updateAnswer(url,aid,answer)
    {
        if (answeruploading === false){
            answeruploading = true;
            startupload();
            prequest(url,'POST',{aid:aid,answer:answer},function (res) {
                //console.log('用户修改回答',url,res);
                if (res.code == 1){
                    completeupload();
                    answeruploading=false;
                    var qid = $$('#Question').data('id');
                    mainView.router.reloadPage('question.html?qid='+qid);
                }else{
                    failupload();
                    answeruploading=false;
                }
            },function(){
                //console.log('ajax error');
                failupload();
                answeruploading=false;
            });
        }

    }
    /******答案页面******/
    function getAnswerById(aid,url)
    {
        request(url,'POST',{aid:aid,uid:GlobalUserid},function (res) {
            //console.log('答案页信息',url,res);
            if (res.code=1){
                var title = res.data.question+'-'+res.data.userName+'的回答';
                $$('#Answer').data('sharetitle',title);
                var desc = res.data.answer.replace(/<.*>/g,"").substr(0,30)+'...';
                $$('#Answer').data('sharedesc',desc);

                if ($$('.view-main').data('page')==='Answer'){
                    var aid = $$('#Answer').data('id');
                    var url = Share_url+'&page=answer'+'&param=aid.'+aid;
                    setShare(title,url,desc);
                }

                var navhtml = Nldouapp.AdetailnavTemplate(res.data);
                var chtml = Nldouapp.AdetailcontentTemplate(res.data);
                var tbhtml = Nldouapp.AdetailtoolbarTemplate(res.data);
                $$('.answernav').html(navhtml);
                $$('#Answer').append(tbhtml);
                $$('#Answer .page-content .answer-content').html(chtml);
            }
        });
    }
    function getCommentsByAid(aid,page,url,sort,append)
    {
        request(url,'POST',{aid:aid,page:page,sort:sort,pagesize:answerpagesize,uid:GlobalUserid},function (res) {
            //console.log('答案评论列表',url,res);
            if (res.code == 1){
                var html = Nldouapp.CommentitemTemplate(res.data);
                if (!append) {
                    $$('#Answer .commentlist').find('.citem').remove();
                    $$('#Answer .infinite-scroll').find('.infinite-scroll-preloader').remove();
                    var modal = '<div class="infinite-scroll-preloader">'+
                        '<div class="preloader"></div>'+
                        '</div>';
                    $$('#Answer .infinite-scroll').append(modal);
                    Nldouapp.attachInfiniteScroll('#Answer .infinite-scroll');
                    sofa(res.data.comment.length,$$('#Answer .commentlist'));
                }
                $$('#Answer .commentlist').append(html);
            }
            if (res.data.end == 1){
                Nldouapp.detachInfiniteScroll($$('#Answer .infinite-scroll'));
                $$('#Answer .infinite-scroll-preloader').remove();
            }
            sofa($$('#Answer .commentlist .citem').length,$$('#Answer .commentlist'));
            answerloading = false;
        });
    }
    function agreeAnswer(aid,url)
    {
        prequest(url,'POST',{aid:aid,uid:GlobalUserid},function (res) {
            agreestatus = false;
            //console.log('用户赞同答案',url,res);
        },function () {
            agreestatus = false;
            Nldouapp.alert('系统繁忙，请重试','');
        })
    }
    function cancelagreeAnswer(aid,url)
    {
        prequest(url,'POST',{aid:aid,uid:GlobalUserid},function (res) {
            agreestatus = false;
            //console.log('用户取消答案赞同',url,res);
        },function () {
            agreestatus = false;
            Nldouapp.alert('系统繁忙，请重试','');
        });
    }
    function collectAnswer(aid,url)
    {
        prequest(url,'POST',{aid:aid,uid:GlobalUserid},function (res) {
            collstatus = false;
            //console.log('用户收藏答案',url,res);
        },function () {
            collstatus = false;
            Nldouapp.alert('系统繁忙，请重试','');
        });
    }
    function cancelcollectAnswer(aid,url)
    {
        prequest(url,'POST',{aid:aid,uid:GlobalUserid},function (res) {
            //console.log('用户取消答案收藏',url,res);
            collstatus = false;
        },function () {
            collstatus = false;
            Nldouapp.alert('系统繁忙，请重试','');
        });
    }
    /******发布答案评论页面******/
    function checkComment(comment)
    {
        var wc = parseInt(comment.replace(/\s/g,"").length);
        if (wc === 0) {
            Nldouapp.alert('请输入评论内容');
            return false;
        }
        comment = comment.replace(/\n|\r\n|\r/g,'<br>');
        return comment;
    }
    function addComment(url,aid,uid,comment)
    {
        if (commentuploading === false){
            commentuploading = true;
            startupload();
            prequest(url,'POST',{aid:aid,uid:uid,comment:comment},function (res) {
                //console.log('用户添加评论',url,res);
                if (res.code == 1){
                    completeupload();
                    commentuploading = false;
                    var aid = $$('#Answer').data('id');
                    mainView.router.reloadPage('answer.html?aid='+aid);
                }else{
                    failupload();
                    commentuploading = false;
                }
            },function() {
                //console.log('ajax error');
                failupload();
                commentuploading = false;
            });
        }
    }
    function thumbupComment(cid,url)
    {
        prequest(url,'POST',{cid:cid,uid:GlobalUserid},function (res) {
            thumbupstatus = false;
            //console.log('用户点赞评论',url,res);
        },function () {
            thumbupstatus = false;
            Nldouapp.alert('系统繁忙，请重试','');
        });
    }
    function cancelthumbupComment(cid,url)
    {
        prequest(url,'POST',{cid:cid,uid:GlobalUserid},function (res) {
            thumbupstatus = false;
            //console.log('用户取消点赞评论',url,res);
        },function () {
            thumbupstatus = false;
            Nldouapp.alert('系统繁忙，请重试','');
        });
    }
    /******发布评论回复页面******/
    function checkResponse(comment)
    {
        var wc = parseInt(comment.replace(/\s/g,"").length);
        if (wc === 0) {
            Nldouapp.alert('请输入回复内容');
            return false;
        }
        comment = comment.replace(/\n|\r\n|\r/g,'<br>');
        return comment;
    }
    function responseComment(url,cid,uid,comment)
    {
        if (responseuploading === false){
            responseuploading = true;
            startupload();
            prequest(url,'POST',{cid:cid,uid:uid,comment:comment},function (res) {
                //console.log('用户添加回复',url,res);
                if (res.code == 1){
                    completeupload();
                    responseuploading = false;
                    var aid = $$('#Answer').data('id');
                    mainView.router.reloadPage('answer.html?aid='+aid);
                }else{
                    failupload();
                    responseuploading = false;
                }
            },function() {
                //console.log('ajax error');
                failupload();
                responseuploading = false;
            })
        }
    }
    /******评论回复页面******/
    function getResponseByCid(cid,page,url)
    {
        request(url,'POST',{cid:cid,page:page,pagesize:responsepagesize},function (res) {
            //console.log('评论回复列表',url,res);
            if (res.code == 1){
                var html = Nldouapp.ResponseitemTemplate(res.data.response);
                $$('#Response .response-wrap ul').append(html);
            }
            if (res.data.end == 1){
                Nldouapp.detachInfiniteScroll($$('#Response .infinite-scroll'));
                $$('#Response .infinite-scroll-preloader').remove();
            }
            responseloading = false;
        });
    }

    var $$ = Dom7;
    var GlobalUserid,GlobalOpenid,GlobalFirst;
    var Sysmsgnum=0;
    var Usermsgnum=0;
// var Globaltoken;
// var Commappid = '1asffnae6ue8';
    var ApiUrl = 'http://api.nldou.com/';
    var initjssdk_url = ApiUrl+'weixinapi/init_wx_jsapi';
    var Prepay_url = ApiUrl+'wxpay/prepay';
// var Nativepay_url = ApiUrl+'wxpay/nativepay';
    var Share_url = ApiUrl+'ucenter/weixinlogin?pid=7653';
    var Sharecallback_url = ApiUrl+'commwapucenter/sharecallback';
    var Shareimg_url = 'http://wap.nldou.com/comm/img/comm-logo.jpg';

    var Qrank_url = ApiUrl+'commwapbeans/getQuestionrank';
    var Qresponsed_url = ApiUrl+'commwapbeans/getQResponsed';
    var GetNotifyCount_url = ApiUrl+'commwapnotify/getNotifyUnread';
    var GetUserNotify_url = ApiUrl+'commwapnotify/getUserNotify';
    var GetSysNotify_url = ApiUrl+'commwapnotify/getSysnotify';
    var ReadNotify_url = ApiUrl+'commwapnotify/readNotify';
    var ClearNotify_url = ApiUrl+'commwapnotify/clearNotify';
//discover controller
    var CheckUserLogin_url = ApiUrl+'ucenter/checkUserLogin';
    var CheckUserRedirect_url = ApiUrl+'ucenter/weixinlogin?pid=7653';
    var GetDiscoverData_url = ApiUrl+'commwapdiscover/';
    var GetDiscoverQuestion_url = ApiUrl+'commwapdiscover/getQuestion';
//question controller
    var AddQuestionViews_url = ApiUrl+'commwapquestion/readQuestion';
    var GetQuestionQdetail_url = ApiUrl+'commwapquestion/';
    var GetQuestionAitem_url = ApiUrl+'commwapquestion/getAnswer';
    var FollowQuestion_url = ApiUrl+'commwapquestion/followQuestion';
    var CancelFollowQuestion_url = ApiUrl+'commwapquestion/cancelfollowQuestion';
    var GetQuestionSubject_url = ApiUrl+'commwapquestion/getSubject';
    var AddQuestion_url = ApiUrl+'commwapquestion/addQuestion';
    var Beansrank_url = ApiUrl+'commwapbeans/getBeansrankByQid';
    var Dechargebeans_url = ApiUrl+'commwapbeans/dechargebeans';
    var Getcontributer_url = ApiUrl+'commwapquestion/getQContributer';
//answer controller
    var AddAnswer_url = ApiUrl+'commwapanswer/addAnswer';
    var UpdateAnswer_url = ApiUrl+'commwapanswer/updateAnswer';
    var CheckAnswerExist_url = ApiUrl+'commwapanswer/checkAnswerExist';
    var GetAnwserAdetail_url = ApiUrl+'commwapanswer/';
    var AgreeAnswer_url = ApiUrl+'commwapanswer/agreeAnswer';
    var CancelAgreeAnswer_url = ApiUrl+'commwapanswer/cancelagreeAnswer';
    var CollectAnswer_url = ApiUrl+'commwapanswer/collectAnswer';
    var CancelCollectAnswer = ApiUrl+'commwapanswer/cancelcollectAnswer';
    var GetAnswerCitem_url = ApiUrl+'commwapanswer/getComment';
    var AddComment_url = ApiUrl+'commwapanswer/addComment';
//comment controller
    var thumbupComment_url = ApiUrl+'commwapcomment/thumbup';
    var cancelThumbup_url = ApiUrl+'commwapcomment/cancelThumbup';
    var AddResponse_url = ApiUrl+'commwapcomment/responseComm';
    var GetCommentsResponse_url = ApiUrl+'commwapcomment/getResponse';
//subject controller
    var GetSubByid_url = ApiUrl+'commwapsubject/getSubById';
    var FollowSub_url = ApiUrl+'commwapsubject/followSub';
    var CancelFollowSub_url = ApiUrl+'commwapsubject/cancelfollowSub';
    var GetQBySid_url = ApiUrl+'commwapsubject/getQuestionBySid';
//ucenter controller
    var GetUcenterInfo_url = ApiUrl+'commwapucenter/getInfo';
    var Sign_url = ApiUrl+'commwapucenter/sign';
    var GetMyfollowq_url = ApiUrl+'commwapucenter/getFollowq';
    var GetMyfollowsub_url = ApiUrl+'commwapucenter/getFollowsub';
    var GetMycollect_url = ApiUrl+'commwapucenter/getCollects';
    var GetMyanswer_url = ApiUrl+'commwapucenter/getUserAnswer';
    var GetMyquestion_url = ApiUrl+'commwapucenter/getUserQuestion';
    var Chargeuser_url = ApiUrl+'commwapucenter/getUserInfo';
    var Uploadimg_url = ApiUrl+'commwapucenter/changeIcon';
    var Getprofile_url = ApiUrl+'commwapucenter/getProfile';
    var Getcity_url = ApiUrl+'gamer/getCityList';
    var Getarea_url = ApiUrl+'gamer/getAreaListBycity';
    var Subprofile_url = ApiUrl+'commwapucenter/updateProfile';

    var discoverpagesize = 5;/*发现页问题列表*/
    var questionpagesize = 5;/*问题页答案列表*/
    var contripagesize = 20;/*问题页贡献者展示最大个数*/
    var rankpagesize = 10;/*贡献榜列表*/
    var answerpagesize = 5;/*答案页评论列表*/
    var responsepagesize = 20;/*答案页评论列表*/
    var subjectpagesize = 5;/*话题页问题列表*/
    var myfollowspagesize = 10;/*个人中心我的关注列表*/
    var mycollectspagesize = 5;/*个人中心我的收藏列表*/
    var myanswerpagesize = 5;/*个人中心我的回答列表*/
    var myquestionpagesize = 5;/*个人中心我的提问列表*/
    var notifypagesize = 10;/*消息列表*/

    var discoverloading = false;/*发现页问题列表下拉刷新状态*/
    var questionloading = false;/*问题页答案列表下拉刷新状态*/
    var rankloading = false;/*贡献榜下拉刷新状态*/
    var qrankloading = false;/*女神榜下拉刷新状态*/
    var answerloading = false;/*答案页评论列表下拉刷新状态*/
    var responseloading = false;/*答案页评论回复列表下拉刷新状态*/
    var subjectloading = false;/*话题页评问题列表下拉刷新状态*/
    var myfollowsloading = false;/*个人中心我的关注列表下拉刷新状态*/
    var mycollectsloading = false;/*个人中心我的收藏列表下拉刷新状态*/
    var myanswerloading = false;/*个人中心我的回答列表下拉刷新状态*/
    var myquestionloading = false;/*个人中心我的提问列表下拉刷新状态*/
    var notifyloading = false;/*消息列表下拉刷新状态*/

    var answeruploading = false;/*答案发布状态*/
    var commentuploading = false;/*评论发布状态*/
    var responseuploading = false;/*回复发布状态*/
    var questionuploading = false;/*问题发布状态*/
    var fsubstatus = false;
    var fqstatus = false;
    var collstatus = false;
    var agreestatus = false;
    var thumbupstatus = false;
    var profileuploading = false;
    var chargestatus = false;
    var dechargestatus = false;

    /******判断登陆状态******/
    checkuserlogin(CheckUserLogin_url,CheckUserRedirect_url);
// GlobalUserid = 3;

    /****微信js sdk初始化****/
    $$.ajax({
        url:initjssdk_url,
        method:"GET",
        data: {fromUrl:window.location.href},
        dataType:'json',
        success: function (res) {
            //console.log('初始化jssdk',res);
            if(res.code==1){
                wx.config({
                    debug: false,
                    appId: res.data.appid,
                    timestamp: res.data.timestamp,
                    nonceStr: res.data.nonceStr,
                    signature: res.data.signature,
                    jsApiList: ['chooseWXPay','onMenuShareTimeline','onMenuShareAppMessage','hideMenuItems','chooseImage'
                        ,'uploadImage','getLocalImgData']
                });
            }
        }
    });
    wx.ready(function () {
        wx.hideMenuItems({
            menuList: ['menuItem:share:qq','menuItem:share:weiboApp','menuItem:share:facebook','menuItem:share:QZone',
                'menuItem:copyUrl','menuItem:openWithQQBrowser','menuItem:openWithSafari']
        });
        wx.onMenuShareTimeline({
            title: '一问奕答',
            link: Share_url,
            imgUrl: Shareimg_url,
            success: function () {
                sharecallback(Share_url,'timeline');
                return true;
            }
        });
        wx.onMenuShareAppMessage({
            title: '一问奕答',
            desc: '复旦大学社会学教授沈奕斐，为您解答家庭教育的各类问题，陪您共走育儿路',
            link: Share_url,
            imgUrl: Shareimg_url,
            type: 'link',
            success: function () {
                sharecallback(Share_url,'appmsg');
                return true;
            }
        });
        $$(document).on('click','.charge-item',function(){
            if (chargestatus) return;
            chargestatus=true;
            var id = parseInt($$(this).data('id'));
            var num = 0;
            switch (id){
                case 1:
                    num = 50;
                    break;
                case 2:
                    num = 100;
                    break;
                case 3:
                    num = 500;
                    break;
                case 4:
                    num = 1000;
                    break;
                case 5:
                    num = 5000;
                    break;
                case 6:
                    num = 10000;
                    break;
                case 7:
                    num = 20000;
                    break;
                case 8:
                    num = 50000;
                    break;
                default:
                    return false;
            }
            pay(num);
        });
        // $$(document).on('click','.othercharge-item',function(){
        //     Nldouapp.prompt('其他数目','',function(val){
        //         var num = checkcharge(val);
        //         pay(num);
        //     });
        // });
    });
    wx.error(function (res) {
    });

    /****Initialize your app****/
    var Nldouapp = new Framework7({
        animateNavBackIcon: true,
        modalTitle:'一问奕答',
        modalButtonOk:'确认',
        modalButtonCancel:'取消',
        template7Pages:true,
        swipeBackPage:false,
        pushState:true,
        pushStateSeparator:'#page/'
    });

    /****Add view****/
    var mainView = Nldouapp.addView('.view-main', {
        dynamicNavbar: true
    });
    /****预编译模板****/
    Nldouapp.SwiperslideTemplate = Template7.compile($$('script#Swiperslide').html());
    Nldouapp.SwiperslideRectTemplate = Template7.compile($$('script#SwiperslideRect').html());
    Nldouapp.NotifylistTemplate = Template7.compile($$('script#Notifylist').html());
    Nldouapp.NotifyiconTemplate = Template7.compile($$('script#Notifyicon').html());
    Nldouapp.Notifyicon2Template = Template7.compile($$('script#Notifyicon2').html());
    Nldouapp.SofaTemplate = Template7.compile($$('script#Sofa').html());
    Nldouapp.EmptyTemplate = Template7.compile($$('script#Empty').html());
    Nldouapp.QitemTemplate = Template7.compile($$('script#Qitem').html());
    Nldouapp.RanklistTemplate = Template7.compile($$('script#Ranklist').html());
    Nldouapp.QranklistTemplate = Template7.compile($$('script#Qranklist').html());
    Nldouapp.QreslistTemplate = Template7.compile($$('script#Qreslist').html());
    Nldouapp.QdetailTemplate = Template7.compile($$('script#Qdetail').html());
    Nldouapp.QdetailwrapTemplate = Template7.compile($$('script#Qdetailwrap').html());
    Nldouapp.QContributerTemplate = Template7.compile($$('script#Contributer').html());
    Nldouapp.AnsweritemTemplate = Template7.compile($$('script#Aitem').html());
    Nldouapp.EditorTemplate = Template7.compile($$('script#Editor').html());
    Nldouapp.QeditorTemplate = Template7.compile($$('script#Qeditor').html());
    Nldouapp.AdetailnavTemplate = Template7.compile($$('script#Adetailnav').html());
    Nldouapp.AdetailtoolbarTemplate= Template7.compile($$('script#Adetailtoolbar').html());
    Nldouapp.AdetailcontentTemplate = Template7.compile($$('script#Adetailcontent').html());
    Nldouapp.CommentitemTemplate = Template7.compile($$('script#Citem').html());
    Nldouapp.ResponseitemTemplate = Template7.compile($$('script#Ritem').html());
    Nldouapp.ResponsnavTemplate = Template7.compile($$('script#Responsenav').html());
    Nldouapp.SubdetailTemplate = Template7.compile($$('script#Subdetail').html());
    Nldouapp.UcHeaderTemplate = Template7.compile($$('script#Ucheader').html());
    Nldouapp.SubitemTemplate = Template7.compile($$('script#Sitem').html());
    Nldouapp.CollectitemTemplate = Template7.compile($$('script#Collectitem').html());
    Nldouapp.MyansweritemTemplate = Template7.compile($$('script#Myansweritem').html());
    Nldouapp.MyquestionitemTemplate = Template7.compile($$('script#Myquestionitem').html());
    Nldouapp.ChargeuserTemplate = Template7.compile($$('script#Chargeuser').html());
    Nldouapp.ProfilelistTemplate = Template7.compile($$('script#Profilelist').html());
    Nldouapp.CitylistTemplate = Template7.compile($$('script#Citylist').html());
    Nldouapp.ArealistTemplate = Template7.compile($$('script#Arealist').html());
    Nldouapp.ChilditemTemplate = Template7.compile($$('script#Childitem').html());

    showNfirst(GlobalFirst);

    /******事件******/
    $$(document).on('click','.toggle-text-icon',function () {
        if ($$(this).hasClass('active')){
            $$(this).removeClass('active');
            $$(this).find('i').html('chevron_down');
            $$(this).parent().find('.toggle-text').css('max-height','100px');
        }else{
            $$(this).addClass('active');
            $$(this).find('i').html('chevron_up');
            $$(this).parent().find('.toggle-text').css('max-height','10000px');
        }
    });
    $$(document).on('click','.dicvbtn',function () {
        if ($$('.view-main').data('page')==='Discover') mainView.router.refreshPage();
        else mainView.router.load({url:'index.html'});
    });
//刷新发现页热门问题
    $$(document).on('click','.refdiscbtn',function(){
        if (discoverloading) return;
        discoverloading = true;
        getQuestion(1,GetDiscoverQuestion_url,false);
    });
//进入消息页面
    $$(document).on('click','.notifybtn',function(){
        mainView.router.load({url:'notify.html'});
    });
//消息
    $$(document).on('click','.unotifylistbtn',function () {
        $$('.nlistbtn.active').removeClass('active');
        $$(this).addClass('active');
        $$('#Notify .notifylistwrap').data('type','user');
        getUserNotify(GetUserNotify_url,1,false);
    });
//系统通知
    $$(document).on('click','.sysnotifylistbtn',function () {
        $$('.nlistbtn.active').removeClass('active');
        $$(this).addClass('active');
        $$('#Notify .notifylistwrap').data('type','sys');
        getSysNotify(GetSysNotify_url,1,false);
    });
//阅读消息
    $$(document).on('click','.nitem',function () {
        var type = $$(this).data('msgtype');
        var id = $$(this).data('msgid');
        readNotify(ReadNotify_url,id,type);
    });
//删除消息
    $$(document).on('click','.nitem-delete',function () {
        var type = $$(this).data('msgtype');
        var id = $$(this).data('msgid');
        readNotify(ReadNotify_url,id,type);
    });
//清空消息
    $$(document).on('click','.clearnotifybtn',function () {
        Nldouapp.confirm('确定清空所有消息？','',function(){
            clearNotify(ClearNotify_url);
        });
    });
//进入问题页面
    $$(document).on('click','.qitem',function () {
        var qid = $$(this).data('qid');
        //增加阅读量
        // readQuestion(AddQuestionViews_url,qid);
        mainView.router.load({url:'question.html?qid='+qid});
    });
//进入问题贡献榜
    $$(document).on('click','.conitem',function () {
        var qid = $$("#Question").data('id');
        mainView.router.load({url:'beansrank.html?qid='+qid});
    });
//进入女神榜
    $$(document).on('click','.qrankbtn',function () {
        mainView.router.load({url:'questionrank.html'});
    });
//女神榜未回答
    $$(document).on('click','.qranklistbtn',function () {
        $$('.qlistbtn.active').removeClass('active');
        $$(this).addClass('active');
        $$('#Questionrank .qlistwrap').data('type','rank');
        getQrank(Qrank_url,1);
    });
//女神榜已回答
    $$(document).on('click','.qreslistbtn',function () {
        $$('.qlistbtn.active').removeClass('active');
        $$(this).addClass('active');
        $$('#Questionrank .qlistwrap').data('type','res');
        getQresponsed(Qresponsed_url,1,false);
    });
//进入话题页面
    $$(document).on('click','.subitem',function () {
        var sid = $$(this).data('sid');
        mainView.router.load({url:'subject.html?sid='+sid});
    });
//进入个人中心
    $$(document).on('click','.ucbtn',function(){
        mainView.router.load({url:'ucenter.html'});
    });
//上传头像
    $$(document).on('click','.editiconbtn',function (){
        wx.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success: function (res) {
                changeicon(res.localIds[0]);
            }
        });
    });
//个人中心我的关注
    $$(document).on('click','.myfollows',function () {
        mainView.router.load({url:'myFollows.html'});
    });
//个人中心我的关注->问题
    $$(document).on('click','.myfollowqbtn',function () {
        $$('.followbtn.active').removeClass('active');
        $$(this).addClass('active');
        $$('#Myfollows .followlist').data('type','question');
        getMyfollowq(GetMyfollowq_url,1,false);
    });
//个人中心我的关注->话题
    $$(document).on('click','.myfollowsubbtn',function () {
        $$('.followbtn.active').removeClass('active');
        $$(this).addClass('active');
        $$('#Myfollows .followlist').data('type','subject');
        getMyfollowsub(GetMyfollowsub_url,1,false);
    });
//个人中心我的收藏
    $$(document).on('click','.myCollects',function () {
        mainView.router.load({url:'myCollects.html'});
    });
//个人中心我的回答
    $$(document).on('click','.myAnswers',function () {
        mainView.router.load({url:'myAnswers.html'});
    });
//个人中心我的提问
    $$(document).on('click','.myQuestions',function () {
        mainView.router.load({url:'myQuestions.html'});
    });
//个人中心签到
    $$(document).on('click','.signbtn',function () {
        signToday(Sign_url);
    });
//个人中心充值
    $$(document).on('click','.beansbtn',function () {
        mainView.router.load({url:'chargebeans.html'});
    });
//编辑个人信息
    $$(document).on('click','.editprofile',function () {
        mainView.router.load({url:'profile.html'});
    });
//添加孩子信息
    $$(document).on('click','.addchildbtn',function () {
        mainView.router.load({url:'childinfo.html'});
    });
    var childdelte = [];
//删除孩子信息
    $$(document).on('click','.childitem',function () {
        Nldouapp.swipeoutOpen($$(this), 'right');
    });
    $$(document).on('click','.childitem-delete',function () {
        var id = parseInt($$(this).data('id'));
        childdelte.push(id);
    });
//提交个人信息
    $$(document).on('click','.subprofile',function () {
        if (profileuploading) return;
        profileuploading = true;
        var data = checkProfile();
        if (data) subprofile(data);
    });
//如何赚取能量豆
    $$(document).on('click','.beansguide',function () {
        mainView.router.load({url:'beansguide.html'});
    });
//关注话题
    $$(document).on('click','.subfollowbtn',function () {
        if (fsubstatus) return;
        fsubstatus = true;
        var sid = $$('#Subject').data('id');
        followSub(FollowSub_url,sid);
        var parent = $$(this).parent();
        $$(this).remove();
        var html = '<span class="bg-gray border-r5 color-white subfollowcancelbtn size-14" style="line-height: 30px;width: 70px;height: 30px;text-align: center;">已关注</span>';
        parent.append(html);
    });
//话题取消关注
    $$(document).on('click','.subfollowcancelbtn',function () {
        if (fsubstatus) return;
        fsubstatus = true;
        var sid = $$('#Subject').data('id');
        cancelfollowSub(CancelFollowSub_url,sid);
        var parent = $$(this).parent();
        $$(this).remove();
        var html = '<div class="color-white bg-green flex-row flex-nowrap flex-justify-around flex-align-center border-r5 subfollowbtn" style="width: 50px;height: 30px;padding:0 10px;">'+
            '<i class="f7-icons color-white" style="height: 100%;">add</i>'+
            '<span style="line-height: 30px;" class="size-14">关注</span>'+
            '</div>';
        parent.append(html);
    });
//话题问题排序模式
    $$(document).on('click',".subsortinput",function () {
        var label = $$(this).find('.item-title').html();
        var sort = $$(this).find('input').val();
        $$('#Subject .subsortbtn').html(label);
        $$('#Subject .infinite-scroll').data('sort',sort);

        var sid = $$('#Subject').data('id');
        getQuestionBysid(GetQBySid_url,1,sid,sort,false);

        Nldouapp.closeModal('.popover-subsort');
    });
//用户提问
    $$(document).on('click','.editqbtn',function(){
        pubQuestion(GetQuestionSubject_url);
    });
//用户取消提问
    $$(document).on('click','.closeqeditbtn',function(){
        Nldouapp.closeModal('.popup-qedit');
        $$('.popup-qedit').remove();
    });
//用户发表提问
    $$(document).on('click','.qeditpub',function(){
        var title = $$('input[name="qtitle"]').val();
        var subject = parseInt($$('select[name="qsub"]').val());
        var desc = $$('textarea[name="qdesc"]').val();
        var res = checkQuestion(title,subject,desc);
        if (res) addQuestion(AddQuestion_url,res.subject,res.title,res.desc);
    });
//问题答案排序模式
    $$(document).on('click',".asortinput",function () {
        var label = $$(this).find('.item-title').html();
        var sort = $$(this).find('input').val();
        $$('#Question .asortbtn').html(label);
        $$('#Question .infinite-scroll').data('sort',sort);

        var qid = $$('#Question').data('id');
        getAnswerByQid(qid,1,GetQuestionAitem_url,sort,false);

        Nldouapp.closeModal('.popover-answersort');
    });
//关注问题
    $$(document).on('click','.qfollowbtn',function () {
        if (fqstatus) return;
        fqstatus = true;
        var qid = $$('#Question').data('id');
        followQuestiion(FollowQuestion_url,qid);
        var parent = $$(this).parent();
        $$(this).remove();
        var html = '<span class="bg-gray border-r5 color-white qfollowcancelbtn" style="line-height: 30px;width: 70px;height: 30px;text-align: center;">已关注</span>';
        parent.append(html);

    });
//问题取消关注
    $$(document).on('click','.qfollowcancelbtn',function () {
        if (fqstatus) return;
        fqstatus = true;
        var qid = $$('#Question').data('id');
        cancelfollowQuestiion(CancelFollowQuestion_url,qid);
        var parent = $$(this).parent();
        $$(this).remove();
        var html = '<div class="color-white bg-green flex-row flex-nowrap flex-justify-around flex-align-center border-r5 qfollowbtn" style="width: 50px;height: 30px;padding:0 10px;">'+
            '<i class="f7-icons color-white" style="height: 100%;">add</i>'+
            '<span class="" style="line-height: 30px;">关注</span>'+
            '</div>';
        parent.append(html);
    });
//贡献能量豆
    $$(document).on('click','.givebeans-btn',function () {
        mainView.router.load({url:'dechargebeans.html'});
    });
    $$(document).on('click','.decharge-item',function(){
        if (dechargestatus) return;
        dechargestatus = true;
        var id  = parseInt($$(this).data('id'));
        var qid = $$('#Question').data('id');
        var num = 0;
        switch (id){
            case 1:
                num = 50;
                break;
            case 2:
                num = 100;
                break;
            case 3:
                num = 500;
                break;
            case 4:
                num = 1000;
                break;
            case 5:
                num = 5000;
                break;
            case 6:
                num = 10000;
                break;
            default:
                return false;
        }
        dechargebeans(Dechargebeans_url,num,qid);
    });
    $$(document).on('click','.otherdecharge-item',function(){
        var qid = $$('#Question').data('id');
        Nldouapp.prompt('其他数目','',function(val){
            dechargebeans(Dechargebeans_url,val,qid);
        });
    });
//用户发布答案
    $$(document).on('click','.editanswerbtn',function(){
        var id = $$('#Question').data('id');
        //判断用户是否已经回答过
        //如果回答过，修改答案
        checkAnswerExist(CheckAnswerExist_url,id,GlobalUserid);
    });
//用户发布评论
    $$(document).on('click','.commentbtn',function () {
        var aid = $$(this).data('aid');
        var html = Nldouapp.EditorTemplate({'id':aid,'cid':'','type':'addComment','title':'添加评论','suggest':'填写评论内容','content':''});
        $$('body').append(html);
        Nldouapp.popup('.popup-edit');

    });
//用户发布回复
    $$(document).on("click",".responsebtn",function () {
        var cid = $$(this).data('cid');
        var html = Nldouapp.EditorTemplate({'id':cid,'cid':'','type':'addResponse','title':'添加回复','suggest':'填写回复内容','content':''});
        $$('body').append(html);
        Nldouapp.popup('.popup-edit');
    });
//用户取消发布
    $$(document).on('click','.closeeditbtn',function(){
        Nldouapp.closeModal('.popup-edit');
        $$('.popup-edit').remove();
    });
//用户发布
    $$(document).on('click','.editpub',function(){
        var id = $$(this).data('id');
        var cid = $$(this).data('cid');
        var type = $$(this).data('type');
        var content = $$('textarea[name="editcontent"]').val();
        switch (type){
            case 'updateAnswer':
                //校验用户输入内容
                content = checkAnswer(content);
                if (!content) return;
                updateAnswer(UpdateAnswer_url,cid,content);
                break;
            case 'addAnswer':
                content = checkAnswer(content);
                if (!content) return;
                addAnswer(AddAnswer_url,id,GlobalUserid,content);
                break;
            case 'addComment':
                content = checkComment(content);
                if (!content) return;
                addComment(AddComment_url,id,GlobalUserid,content);
                break;
            case 'addResponse':
                content = checkResponse(content);
                if (!content) return;
                responseComment(AddResponse_url,id,GlobalUserid,content);
                break;
            default:
        }
    });
//用户点击答案
    $$(document).on('click','.aitem',function () {
        var aid = $$(this).data('aid');
        mainView.router.load({url:'answer.html?aid='+aid});
    });
//用户点击赞同
    $$(document).on('click','.agreebtn',function () {
        if (agreestatus) return;
        agreestatus = true;
        var aid = $$(this).data('aid');
        agreeAnswer(aid,AgreeAnswer_url);
        var agreenum = parseInt($$(this).data('agrees'))+1;
        var html = '<div class="cancelagreebtn active" data-aid="'+aid+'" data-agrees="'+agreenum+'">'+
            '<div class="toolbar-icon-item flex-column flex-justify-between flex-align-center flex-wrap">'+
            '<i class="toolbar-icon f7-icons">heart_fill</i>'+
            '<span class="toolbar-icon-text">已赞同('+agreenum+')</span>'+
            '</div></div>';
        $$(this).parent().html(html);
    });
//用户取消赞同
    $$(document).on('click','.cancelagreebtn',function () {
        if (agreestatus) return;
        agreestatus = true;
        var aid = $$(this).data('aid');
        cancelagreeAnswer(aid,CancelAgreeAnswer_url);
        var agreenum = parseInt($$(this).data('agrees'))-1;
        var html = '<div class="agreebtn" data-aid="'+aid+'" data-agrees="'+agreenum+'">'+
            '<div class="toolbar-icon-item flex-column flex-justify-between flex-align-center flex-wrap">'+
            '<i class="toolbar-icon f7-icons">heart_fill</i>'+
            '<span class="toolbar-icon-text">赞同('+agreenum+')</span>'+
            '</div></div>';
        $$(this).parent().html(html);
    });
//用户点击收藏
    $$(document).on('click','.collectbtn',function () {
        if (collstatus) return;
        collstatus = true;
        var aid = $$(this).data('aid');
        collectAnswer(aid,CollectAnswer_url);
        var collectnum = parseInt($$(this).data('collects'))+1;
        var html = '<div class="cancelcollectbtn active" data-aid="'+aid+'" data-collects="'+collectnum+'">'+
            '<div class="toolbar-icon-item flex-column flex-justify-between flex-align-center flex-wrap">'+
            '<i class="toolbar-icon f7-icons">star_fill</i>'+
            '<span class="toolbar-icon-text">已收藏('+collectnum+') </span>'+
            '</div></div>';
        $$(this).parent().html(html);
    });
//用户取消收藏
    $$(document).on('click','.cancelcollectbtn',function () {
        if (collstatus) return;
        collstatus = true;
        var aid = $$(this).data('aid');
        cancelcollectAnswer(aid,CancelCollectAnswer);
        var collectnum = parseInt($$(this).data('collects'))-1;
        var html = '<div class="collectbtn" data-aid="'+aid+'" data-collects="'+collectnum+'">'+
            '<div class="toolbar-icon-item flex-column flex-justify-between flex-align-center flex-wrap">'+
            '<i class="toolbar-icon f7-icons">star_fill</i>'+
            '<span class="toolbar-icon-text">加入收藏('+collectnum+') </span>'+
            '</div></div>';
        $$(this).parent().html(html);
    });
//答案评论排序模式
    $$(document).on('click',".csortinput",function () {
        var label = $$(this).find('.item-title').html();
        var sort = $$(this).find('input').val();
        $$('#Answer .csortbtn').html(label);
        $$('#Answer .infinite-scroll').data('sort',sort);

        var aid = $$('#Answer').data('id');
        getCommentsByAid(aid,1,GetAnswerCitem_url,sort,false);

        Nldouapp.closeModal('.popover-commentsort');
    });
//用户评论点赞
    $$(document).on("click",".thumbupbtn",function () {
        if (thumbupstatus) return;
        thumbupstatus = true;
        var cid = $$(this).data('cid');
        thumbupComment(cid,thumbupComment_url);
        var thumbnum = parseInt($$(this).data('thumbup'))+1;
        var html = '<div class="cancelthumbupbtn flex-row flex-nowrap flex-justify-between flex-align-center" data-cid="'+cid+'" data-thumbup="'+thumbnum+'" ' +
            'style="width: 25px;">'+
            '<i class="f7-icons size-12">heart_fill</i>'+
            '<span>'+thumbnum+'</span>'+
            '</div>';
        $$(this).parent().html(html);
    });
//用户评论点赞
    $$(document).on("click",".cancelthumbupbtn",function () {
        if (thumbupstatus) return;
        thumbupstatus = true;
        var cid = $$(this).data('cid');
        cancelthumbupComment(cid,cancelThumbup_url);
        var thumbnum = parseInt($$(this).data('thumbup'))-1;
        var html = '<div class="thumbupbtn flex-row flex-nowrap flex-justify-between flex-align-center" data-cid="'+cid+'" data-thumbup="'+thumbnum+'" ' +
            'style="width: 30px;">'+
            '<i class="f7-icons size-12">heart</i>'+
            '<span>'+thumbnum+'</span>'+
            '</div>';
        $$(this).parent().html(html);
    });
//用户查看回复
    $$(document).on("click",".showresponse",function () {
        var cid = $$(this).data('cid');
        var aid = $$('#Answer').data('id');
        mainView.router.load({url:'response.html?cid='+cid+'&aid='+aid});
    });

    Nldouapp.onPageInit('Discover',function () {
        if($$('.view-main').data('page')==='Discover') {
            var title = '一问奕答';
            var desc = '复旦大学社会学教授沈奕斐，为您解答家庭教育的各类问题，陪您共走育儿路';
            setShare(title,Share_url,desc);
        }

        getDiscoverData(GetDiscoverData_url);
        getQuestion(1,GetDiscoverQuestion_url,true);
        getNotifyCount(GetNotifyCount_url);

        $$('#Discover .infinite-scroll').on('infinite', function () {
            if (discoverloading) return;
            discoverloading = true;
            var lastIndex = parseInt($$("#Discover .qlist .qitem").length);
            var page = lastIndex/discoverpagesize + 1;
            getQuestion(page,GetDiscoverQuestion_url,true);
        });
    }).trigger();
    Nldouapp.onPageInit('Notify',function(){
        //分类显示未读消息数量
        var uhtml = Nldouapp.Notifyicon2Template({unread:Usermsgnum});
        var shtml = Nldouapp.Notifyicon2Template({unread:Sysmsgnum});
        $$('.notifynav .notifylisticon').remove();
        $$('.notifynav .unotifylistbtn').append(uhtml);
        $$('.notifynav .sysnotifylistbtn').append(shtml);
        //获取未读用户消息
        getUserNotify(GetUserNotify_url,1,true);
        $$('#Notify .infinite-scroll').on('infinite', function () {
            if (notifyloading) return;
            notifyloading = true;
            var list = $$("#Notify .notifylistwrap");
            var lastIndex = parseInt(list.find('li').length);
            var page = lastIndex/notifypagesize + 1;
            var listtype = list.data('type');
            switch (listtype){
                case 'user':
                    getUserNotify(GetUserNotify_url,page,true);
                    break;
                case 'sys':
                    getSysNotify(GetSysNotify_url,page,true);
                    break;
            }
        });
    });
    Nldouapp.onPageAfterBack('Notify',function(){
        getNotifyCount(GetNotifyCount_url);
    });
    Nldouapp.onPageInit('Subject',function (page) {
        var sid = page.query.sid;
        $$('#Subject').data('id',sid);
        getSubById(GetSubByid_url,sid);
        getQuestionBysid(GetQBySid_url,1,sid,'score',true);
        getNotifyCount(GetNotifyCount_url);

        $$('#Subject .infinite-scroll').on('infinite', function () {
            if (subjectloading) return;
            subjectloading = true;
            var sort = $$(this).data('sort');
            var lastIndex = parseInt($$("#Subject .qlist .qitem").length);
            var page = lastIndex/subjectpagesize + 1;
            getQuestionBysid(GetQBySid_url,page,sid,sort,true);
        });
    });
    Nldouapp.onPageAfterBack('Subject',function(){
        var shareobj = getShareContent();
        setShare(shareobj.title,shareobj.url,shareobj.desc);
    });
    Nldouapp.onPageInit('Question',function(page){
        var qid = page.query.qid;
        $$('#Question').data('id',qid);

        getQuestionById(qid,GetQuestionQdetail_url);
        getAnswerByQid(qid,1,GetQuestionAitem_url,'score',true);
        getNotifyCount(GetNotifyCount_url);
        readQuestion(AddQuestionViews_url,qid);

        $$('#Question .infinite-scroll').on('infinite', function () {
            if (questionloading) return;
            questionloading = true;
            var sort = $$(this).data('sort');
            var lastIndex = parseInt($$("#Question .answerlist .aitem").length);
            var page = lastIndex/questionpagesize + 1;
            getAnswerByQid(qid,page,GetQuestionAitem_url,sort,true);
        });
    });
    Nldouapp.onPageAfterBack('Question',function(){
        var shareobj = getShareContent();
        setShare(shareobj.title,shareobj.url,shareobj.desc);
    });
    Nldouapp.onPageInit('Beansrank',function (page) {
        var qid = page.query.qid;
        getBeansrankByqid(Beansrank_url,1,qid);
        $$('#Beansrank .infinite-scroll').on('infinite',function () {
            if (rankloading) return;
            rankloading = true;
            var lastIndex = parseInt($$("#Beansrank .beansranklist li").length);
            var page = lastIndex/rankpagesize + 1;
            getBeansrankByqid(Beansrank_url,page,qid);
            rankloading = false;
        });
    });
    Nldouapp.onPageInit('Questionrank',function (page){
        if($$('.view-main').data('page')==='Questionrank') {
            var title = '一问奕答女神榜';
            var desc = '您的朋友邀请您，为他困扰的问题贡献一份力哦~~';
            var url = Share_url + '&page=questionrank';
            setShare(title, url, desc);
        }

        getQrank(Qrank_url,1);
        $$('#Questionrank .infinite-scroll').on('infinite', function () {
            if (qrankloading) return;
            qrankloading = true;
            var list = $$("#Questionrank .qlistwrap");
            var lastIndex = parseInt(list.find('a').length);
            var page = lastIndex/rankpagesize + 1;
            var listtype = list.data('type');
            switch (listtype){
                case 'rank':
                    getQrank(Qrank_url,page);
                    break;
                case 'res':
                    getQresponsed(Qresponsed_url,page,true);
                    break;
            }
        });
    });
    Nldouapp.onPageAfterBack('Questionrank',function(){
        var shareobj = getShareContent();
        setShare(shareobj.title,shareobj.url,shareobj.desc);
    });
    Nldouapp.onPageInit('Answer',function(page){
        var aid = page.query.aid;
        $$('#Answer').data('id',aid);
        getAnswerById(aid,GetAnwserAdetail_url);
        getCommentsByAid(aid,1,GetAnswerCitem_url,'score',true);

        $$('#Answer .infinite-scroll').on('infinite', function () {
            if (answerloading) return;
            answerloading = true;
            var sort = $$(this).data('sort');
            var lastIndex = parseInt($$("#Answer .commentlist .citem").length);
            var page = lastIndex/answerpagesize + 1;
            getCommentsByAid(aid,page,GetAnswerCitem_url,sort,true);
        });
    });
    Nldouapp.onPageAfterBack('Answer',function(){
        var shareobj = getShareContent();
        setShare(shareobj.title,shareobj.url,shareobj.desc);
    });
    Nldouapp.onPageInit('Response',function (page) {
        var cid = page.query.cid;
        var aid = page.query.aid;
        var rnavhtml = Nldouapp.ResponsnavTemplate({aid:aid});
        $$('.responsenav').html(rnavhtml);
        getResponseByCid(cid,1,GetCommentsResponse_url);

        $$('#Response .infinite-scroll').on('infinite',function () {
            if (responseloading) return;
            responseloading = true;
            var lastIndex = parseInt($$("#Response .response-wrap li").length);
            var page = lastIndex/responsepagesize + 1;
            getResponseByCid(cid,page,GetCommentsResponse_url);
        });
    });
    Nldouapp.onPageInit('Ucenter',function () {
        if($$('.view-main').data('page')==='Ucenter') {
            var title = '一问奕答';
            var desc = '复旦大学社会学教授沈奕斐，为您解答家庭教育的各类问题，陪您共走育儿路';
            setShare(title,Share_url,desc);
        }
        getUcInfo(GetUcenterInfo_url);
        getNotifyCount(GetNotifyCount_url);
    });
    Nldouapp.onPageAfterBack('Ucenter',function(){
        var shareobj = getShareContent();
        setShare(shareobj.title,shareobj.url,shareobj.desc);
    });
    Nldouapp.onPageInit('Chargebeans',function () {
        getChargeUser(Chargeuser_url);
    });
    Nldouapp.onPageInit('Dechargebeans',function () {
        getDechargeUser(Chargeuser_url);
    });
    Nldouapp.onPageInit('Myfollows',function () {
        getMyfollowq(GetMyfollowq_url,1,true);
        $$('#Myfollows .infinite-scroll').on('infinite', function () {
            if (myfollowsloading) return;
            myfollowsloading = true;
            var list = $$("#Myfollows .followlist");
            var lastIndex = parseInt(list.find('a').length);
            var page = lastIndex/myfollowspagesize + 1;
            var listtype = list.data('type');
            switch (listtype){
                case 'question':
                    getMyfollowq(GetMyfollowq_url,page,true);
                    break;
                case 'subject':
                    getMyfollowsub(GetMyfollowsub_url,page,true);
                    break;
            }
        });
    });
    Nldouapp.onPageInit('Mycollects',function () {
        getMycollect(GetMycollect_url,1,true);
        $$('#Mycollects .infinite-scroll').on('infinite', function () {
            if (mycollectsloading) return;
            mycollectsloading = true;
            var list = $$("#Mycollects .collectlist");
            var lastIndex = parseInt(list.find('.aitem').length);
            var page = lastIndex/mycollectspagesize + 1;
            getMycollect(GetMycollect_url,page,true);
        });
    });
    Nldouapp.onPageInit('Myanswers',function () {
        getMyanswer(GetMyanswer_url,1,true);
        $$('#Myanswers .infinite-scroll').on('infinite', function () {
            if (myanswerloading) return;
            myanswerloading = true;
            var list = $$("#Myanswers .myanswerlist");
            var lastIndex = parseInt(list.find('.aitem').length);
            var page = lastIndex/myanswerpagesize + 1;
            getMyanswer(GetMyanswer_url,page,true);
        });
    });
    Nldouapp.onPageInit('Myquestions',function () {
        getMyquestion(GetMyquestion_url,1,true);

        $$('#Myquestions .infinite-scroll').on('infinite', function () {
            if (myquestionloading) return;
            myquestionloading = true;
            var list = $$("#Myquestions .myqlist");
            var lastIndex = parseInt(list.find('.qitem').length);
            var page = lastIndex/myquestionpagesize + 1;
            getMyquestion(GetMyquestion_url,page,true);
        });
    });
    Nldouapp.onPageInit('Profile',function () {
        getProfile();
    });
    Nldouapp.onPageInit('Childinfo',function () {
        Nldouapp.calendar({
            input:'#cbcal',
            monthNames:['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'],
            weekHeader:false,
            closeOnSelect:true
        });
        $$('.subchild').on('click',function () {
            var cgender = $$('select[name="childgender"]').val();
            var cg = cgender=='m'?'男孩':'女孩';
            var cbirth = $$('input[name="childbirth"]').val();
            var cschool = $$('select[name="childschool"]').val();
            var cs = cschool=='1'?'公立学校':(cschool=='2'?'私立学校':'国际学校');
            var data = [{id:0,gender:cgender,school:cschool,birthDay:cbirth,genderstr:cg,schoolstr:cs}];
            var html = Nldouapp.ChilditemTemplate(data);
            $$('#Profile .child-wrap').append(html);
            mainView.router.back();
        });
    });
}();